<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>消息总线测试</title>
</head>

<body>
    
</body>
<script src="./js/jquery-3.1.1.js"></script>
<script>
    $(function () {
        var reqDataTypeName = {
            "gskk_enex_stats_resp": "按天查询进出站数量",
            "gskk_enex_stats_area_resp": "按区域查询进出站数量",
            "gskk_enex_stats_station_resp": "按站点查询进出站数量",
            "skk_weight_stats_resp": "按天查询进出站重量",
            "gskk_weight_stats_area_resp": "按区域查询进出站重量",
            "gskk_weight_stats_station_resp": "按站点查询进出站重量",
            "tl_cz_name_resp": "根据车站简拼查询车站站名",
            "tl_cz_province_resp": "按省名查询省内车站",
            "tl_cz_time_resp": "按车站、日期查询车站时刻信息",
            "tl_lc_time_resp": "列车时刻表信息",
            "tl_lc_sj_resp": "根据站名、日期、车次查询列车到发实际",
            "tl_lc_df_resp": "根据站名、日期、车次查询列车到发计划",
            "tl_get_zm_resp": "获取站码对照表信息",
            "tl_lclx_xx_resp": "列车类型对照表信息",
            "tl_cz_sxk_resp": "根据车次、日期、车站获取上下车人数（实际）",
            "tl_cz_sxk_ys_resp": "根据车次、日期、车站获取上下车人数（预售）",
            "hlzh_hbdt_resp": "查询机场动态",
            "adsb_aircraft_resp": "查询飞机动态",
            "adsb_aircraft_list_resp": "查询飞机动态列表",
            "fcz_wlhbskb_resp": "查询航班信息",
            "fcz_jcll_resp": "查询机场进出港流量信息",
        };
        var parseCode = {
            "0x0000": "成功",
            "0x0001": "错误的消息内容",
            "0x0002": "错误的参数",
            "0x0003": "IP地址不可达",
            "0x0004": "未初始化",
            "0x0005": "证书未加载",
            "0x0006": "服务不支持",
            "0x0007": "错误的域",
            "0x0008": "错误的类型",
            "0x0009": "错误的订阅类型",
            "0x0100": "其他错误",
            "0x0110": "消息发送超时",
            "0x0111": "消息处理异常",
            "0x0200": "SOCOKE错误",
            "0x0201": "连接为空",
            "0x0202": "连接超时",
            "0x0203": "连接中断",
            "0x0300": "Json错误",
            "0xFFFF": "未知错误",
            "0x7000": "未指定错误",
            "0x7001": "错误的客户端ID",
            "0x7002": "客户端未注册",
            "0x7003": "服务器拒绝",
            "0x7004": "用户数限制",
            "0x7005": "客户端已注册",
            "0x7006": "无效的对方ID",
            "0x7007": "数据内容过大",
            "0x7008": "错误的method字段",
            "0x7009": "call_id字段为空",
            "0x700A": "新证书和原证书不匹配",
            "0x8000": "证书内容错误",
            "0x8001": "无效的证书编号",
            "0x8002": "证书连接地址格式错误",
            "0x8003": "连接地址无权限",
            "0x8004": "订阅类型格式错误",
            "0x8005": "订阅类型无权限",
            "0x8006": "通知类型格式错误",
            "0x8007": "通知类型无权限",
            "0x8008": "证书有效期格式错误",
            "0x8009": "证书不在有效期",
            "0x800A": "发送类型格式错误",
            "0x800B": "发送类型无权限"
        }
        var ws = null,
            boo = false,
            count = 0;
        var resultData,
            sessionId,
            Guid,
            certificate,
            aircraftId, //飞机编号
            resData, //注册数据
            subDat; //订阅信息
        var subsInfo = "@gskk_en@wz.zj;@gskk_ex@wz.zj;@lkxx_yys@;@clw_dynamic_cbais@"; //订阅内容
        var certificate = {
            "info": {
                "ver": 2,
                "sn": "{A5CFE530-F949-44BD-A098-FC5CB5933F84}",
                "user": "杭州皓天信息技术有限公司",
                "begin": "2017-08-10",
                "end": "2017-12-31",
                "area": "",
                "ip": "10.100.254.66;121.40.30.88",
                "idlist": "",
                "subscribe": "@gskk_en@wz.zj;@gskk_ex@wz.zj;@lkxx_yys@;@clw_dynamic_cbais@",
                "notify": "",
                "send": "gskk_enex_stats_req;gskk_enex_stats_area_req;gskk_enex_stats_station_req;gskk_weight_stats_req;gskk_weight_stats_area_req;gskk_weight_stats_station_req;hlzh_hbdt_req;adsb_aircraft_req;adsb_aircraft_list_req;fcz_wlhbskb_req;fcz_jcll_req;tl_cz_name_req;tl_cz_province_req;tl_cz_time_req;tl_lc_time_req;tl_lc_sj_req;tl_lc_df_req;tl_get_zm_req;tl_lclx_xx_req;tl_cz_sxk_req;tl_cz_sxk_ys_req",
                "limit": 3,
                "localhost": false,
                "email": "zhangying@hituns.com",
                "tel": "18856151082",
                "server_id": ""
            },
            "check": "7660ba98d2077fd0bb05e4f14e9a63b3"
        }; //数字证书
        var respType = ["gskk_enex_stats_resp", "gskk_enex_stats_area_resp", "gskk_enex_stats_station_resp",
            "gskk_weight_stats_resp", "gskk_weight_stats_area_resp", "gskk_weight_stats_station_resp",
            "tl_cz_name_resp", "tl_cz_province_resp", "tl_cz_time_resp", "tl_lc_time_resp", "tl_lc_sj_resp",
            "tl_lc_df_resp", "tl_get_zm_resp", "tl_lclx_xx_resp", "tl_cz_sxk_resp", "tl_cz_sxk_ys_resp",
            "hlzh_hbdt_resp", "adsb_aircraft_resp", "adsb_aircraft_list_resp", "fcz_wlhbskb_resp",
            "fcz_jcll_resp",
        ] //响应请求类型
        var numberType = ["en", "ex", "station_id_list_count", "weight"]
        var areaArr = ["hz", "nb", "wz", "tz", "jh", "sx", "hu", "qz", "ls", "zs", "jx"];

        function linkInfoData() { //连接字段
            $('.resp-mesBox').html('');
            Guid = guid();
            websocket();
        }
        linkInfoData();

        function resInfoData(Guid) { //注册字段
            resData = {
                'method': 'REGISTER',
                'type': 'register_req',
                'call_id': Guid,
                'info': {
                    'certificate': JSON.stringify(certificate)
                }
            };
            ws.send(JSON.stringify(resData));
        }

        function subInfoData(sessionId, Guid) { //订阅字段
            subData = {
                "method": "REGISTER",
                "type": "subscribe_req",
                "from": sessionId,
                "call_id": Guid,
                "info": {
                    "subscribe": subsInfo
                }
            }
            if (subsInfo.match(/^\@[A-z]/)) {
                ws.send(JSON.stringify(subData));
            }
        }

        function sendRes(type, serverId, sendData) { //发送查询请求
            var searData = sendData ? sendData : {};
            var data = {
                "method": "INFO",
                "type": type,
                "from": sessionId,
                "to": serverId,
                "call_id": Guid,
                "info": {
                    "data": searData
                }
            }
            ws.send(JSON.stringify(data));
        }

        function websocket() { //websocket初始化
            var respCount = 1, //返回信息累计
                boo1 = boo2 = boo3 = boo4 = false;
            var num = 0;
            if (window.WebSocket) {
                ws = new WebSocket('ws://121.40.30.88:8080');
                ws.onopen = function (event) {
                    if (ws.readyState === WebSocket.OPEN) {
                        resInfoData(Guid);
                    }
                };
                ws.onmessage = function (event) {
                    resultData = JSON.parse(event.data);
                    if (resultData.type == "register_resp") {
                        sessionId = resultData.info.session_id;
                        subInfoData(sessionId, Guid);
                        //高速卡口
                        sendRes("gskk_weight_stats_req", "{11EFDBDB-DE99-48D8-A23F-17AB135736AE}", req);
                        sendRes("gskk_enex_stats_req", "{11EFDBDB-DE99-48D8-A23F-17AB135736AE}", req);
                        sendRes("gskk_enex_stats_area_req", "{11EFDBDB-DE99-48D8-A23F-17AB135736AE}",
                            reqArea);
                        sendRes("gskk_weight_stats_area_req", "{11EFDBDB-DE99-48D8-A23F-17AB135736AE}",
                            reqArea);
                        sendRes("gskk_weight_stats_station_req", "{11EFDBDB-DE99-48D8-A23F-17AB135736AE}",
                            weightStation);
                        sendRes("gskk_enex_stats_station_req", "{11EFDBDB-DE99-48D8-A23F-17AB135736AE}",
                            weightStation);
                        //航空
                        sendRes("hlzh_hbdt_req", "{191A5A0E-7EF7-4044-8214-E190975A951B}", hlzhData);
                        sendRes("adsb_aircraft_list_req", "{0803C95E-B1BF-4264-BDD5-348BEC6DB7A7}");
                        sendRes("fcz_wlhbskb_req", "{D8F91BCC-2442-4EEF-B598-B5ECDFCD3237}", hlwlhbskb);
                        sendRes("fcz_jcll_req", "{D8F91BCC-2442-4EEF-B598-B5ECDFCD3237}", hljcll);
                        //铁路
                        sendRes("tl_cz_province_req", "{FF523A0D-8F04-4FE3-9ACD-A68EFD2F9769}", tlProvince);
                        sendRes("tl_cz_name_req", "{FF523A0D-8F04-4FE3-9ACD-A68EFD2F9769}", tlName);
                        sendRes("tl_cz_time_req", "{FF523A0D-8F04-4FE3-9ACD-A68EFD2F9769}", tlTime);
                        sendRes("tl_lc_time_req", "{FF523A0D-8F04-4FE3-9ACD-A68EFD2F9769}", tlLcTime);
                        sendRes("tl_lc_sj_req", "{FF523A0D-8F04-4FE3-9ACD-A68EFD2F9769}", tlLcsj);
                        sendRes("tl_lc_df_req", "{FF523A0D-8F04-4FE3-9ACD-A68EFD2F9769}", tlLcsj);
                        sendRes("tl_get_zm_req", "{FF523A0D-8F04-4FE3-9ACD-A68EFD2F9769}", tlGet);
                        sendRes("tl_lclx_xx_req", "{FF523A0D-8F04-4FE3-9ACD-A68EFD2F9769}", tlGet);
                        sendRes("tl_cz_sxk_req", "{FF523A0D-8F04-4FE3-9ACD-A68EFD2F9769}", tlsxk);
                        sendRes("tl_cz_sxk_ys_req", "{FF523A0D-8F04-4FE3-9ACD-A68EFD2F9769}", tlsxkys);
                        //保持心跳
                        heartCheck.start();
                    } else if (resultData.type == "adsb_aircraft_list_resp" && !!resultData.info.data && !!resultData.info.data.count) {
                        aircraftId = resultData.info.data.adsb_list[0][1];
                        var hlaircraft = {
                            "aircraft_id": aircraftId
                        }
                        sendRes("adsb_aircraft_req", "{0803C95E-B1BF-4264-BDD5-348BEC6DB7A7}", hlaircraft);
                    } else if (resultData.type != "heart_beat" && !!
                        resultData.type) {
                        if (resultData.type == "@clw_dynamic_cbais@") {
                            var mesResp = resultData.info.message;
                            boo1 = true;
                            if (!mesResp || JSON.stringify(mesResp) == "{}") {
                                postReq(resultData);
                            } else {
                                if (typeof mesResp.cbmc == 'string' &&
                                    typeof mesResp.jd == 'number' && typeof mesResp.wd == 'number' &&
                                    typeof mesResp.sd == 'number' && typeof mesResp.hx == 'number' &&
                                    typeof mesResp.xxlx == 'number') {

                                } else {
                                    postReq(resultData);
                                }
                            }
                        } else if (resultData.type == "@gskk_ex@wz.zj" || resultData.type ==
                            "@gskk_en@wz.zj") {
                            if (resultData.type == "@gskk_ex@wz.zj") {
                                boo2 = true;
                            } else {
                                boo3 = true;
                            }
                            if (resultData.info.data == undefined || resultData.info.data.count ==
                                undefined || resultData.info.data
                                .list == undefined || !resultData.info.data.list instanceof Array) {
                                postReq(resultData);
                            } else {
                                console.log(resultData) //删除
                            }
                        } else if (resultData.type == "@lkxx_yys@") {
                            boo4 = true;
                            if (!resultData.info.datafrom == undefined || !resultData.info.reporttime ==
                                undefined || !resultData.info
                                .traffic == undefined) {
                                postReq(resultData);
                            } else {
                                console.log(resultData) //删除
                            }
                        } else {
                            if (respType.indexOf(resultData.type) > -1) { //不包含返回-1
                                checkResData(resultData.type);
                                respCount++;
                            }
                        }
                        boo = boo1 && boo2 && boo3 && boo4 && respCount == 21; //所有订阅信息和查询信息都响应式boo为true，断开连接，1小时后重连
                        if (boo) {
                            num = num + 1;
                            if (num == 1) {
                                reLink();
                            }
                        }
                    }
                };
                ws.onclose = function (event) {
                    heartCheck.clear();

                };
                ws.onerror = function (event) {};
            } else {
                alert("您的浏览器不支持websocket~");
            }
        }

        var heartCheck = { //心跳
            timeout: 50000, //50s
            timeoutObj: null,
            clear: function () {
                clearInterval(this.timeoutObj);
            },
            start: function () {
                var data = {
                    "method": "INFO",
                    "from": sessionId,
                    "type": "heart_beat",
                    "call_id": Guid
                }
                this.timeoutObj = setInterval(function () {
                    if (ws.readyState === WebSocket.OPEN) {
                        ws.send(JSON.stringify(data));
                    }
                }, this.timeout);
            }
        }

        function reLink() { //重连
            ws.close();
            boo = false;
            setTimeout(function () {
                linkInfoData();
            }, 1000 * 60 * 60); //1000*60*60 一个小时连接一次
        }

        function checkResData(type) { //检查返回的字段是否有误
            if (resultData.type == type) {
                if (resultData.info.result.code === 0 && resultData.info.data != undefined) {
                    for (var key in resultData.info.data) {
                        if (numberType.indexOf(key) > -1) {
                            if (typeof resultData.info.data[key] != "number") {
                                postReq(resultData);
                            }
                        } else if (key == "area") {
                            if (areaArr.indexOf(resultData.info.data[key]) == -1) {
                                postReq(resultData);
                            }
                        }
                    }
                } else {
                    postReq(resultData);
                }
            }
        }

        function getNowFormatDate(num, seperator) { //获取当前时间
            var date = new Date();
            var seperator = seperator ? "-" : "";
            var month = date.getMonth() + 1;
            var strDate = date.getDate() - num;
            if (month >= 1 && month <= 9) {
                month = "0" + month;
            }
            if (strDate >= 0 && strDate <= 9) {
                strDate = "0" + strDate;
            }
            var currentdate = date.getFullYear() + seperator + month + seperator + strDate
            return currentdate;
        }

        //高速卡口查询消息
        var req = {
            "date": getNowFormatDate(0, "-")
        }
        var reqArea = {
            "date": getNowFormatDate(0, "-"),
            "area": "wz"
        }
        var weightStation = {
            "date": getNowFormatDate(0, "-"),
            "station_id_list_count": 1,
            "station_id_list": [1001]
        }

        //航空查询消息
        var hlzhData = {
            "code": "HGH"
        }

        var hlwlhbskb = {
            "fnum": "MU5373"
        }
        var hljcll = {
            "airport": "HGH"
        }
        //铁路查询消息
        var tlProvince = {
            "province": "浙江",
            "code": "ZJ01"
        }
        var tlName = {
            "station": "hz",
            "code": "ZJ01"
        }
        var tlTime = {
            "Station": "嘉善",
            "TrainDate": getNowFormatDate(0),
            "code": "ZJ01"
        }

        var tlLcTime = {
            "train": "G7625",
            "code": "ZJ01"
        }
        var tlLcsj = {
            "station": "杭州东",
            "traindate": getNowFormatDate(0, "-"),
            "traincode": "",
            "code": "ZJ01"
        }
        var tlGet = {
            "code": "ZJ01"
        }
        var tlsxk = {
            "TrainDate": getNowFormatDate(1),
            "TrainCode": "",
            "StationName": "杭州东",
            "code": "ZJ01"
        }
        var tlsxkys = {
            "TrainDate": getNowFormatDate(0),
            "TrainCode": "",
            "StationName": "杭州东",
            "code": "ZJ01"
        }

        function postReq(data) { //小机器人报错请求
            var result = "";
            var resInforData = "";
            if (!!data.info && !!data.info.result) {
                if (data.info.result.code != 0) {
                    result = "#### 错误信息：" + parseCode[parseDecimal(data.info.result.code)];
                }
                if (data.info.result.code == 0 && data.info.data == undefined) {
                    resInforData = "#### 错误信息：无返回数据";
                }
            }
            var postData = JSON.stringify({
                "data": {
                    "token": "https://oapi.dingtalk.com/robot/send?access_token=c357176a9bc1764119090d22c7e15c3dc15c88f93e481a056870a9ded92db774",
                    "msg": {
                        "msgtype": "markdown",
                        "markdown": {
                            "title": "消息总线监控",
                            "text": "#### 数据查询请求类型：" + reqDataTypeName[data.type] + "(" + data.type.replace("resp","req") + ")" + " \n" +
                                result + "\n" +
                                resInforData + "\n"
                        }
                    }
                }
            });
            $.post("http://120.55.85.1:8069/intu/dingtalk_robot", postData);
        }

        function parseDecimal(code) { //转16进制
            var parsed = code.toString(16);
            var sixthParsed = "0x" + (new Array(5 - parsed.length).join('0') + parsed).toUpperCase();
            return sixthParsed;
        }
        
        function guid() {
            function S4() {
                return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
            }
            return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
        }
    });
</script>

</html>